package com.szt.ynb.server.router.aspect;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.szt.ynb.server.router.annotations.Log;
import com.szt.ynb.server.router.common.SessionConst;
import com.szt.ynb.server.router.entity.enums.LogType;
import com.szt.ynb.server.router.pojo.SessionUser;
import com.szt.ynb.server.router.service.LogService;

/***
 * 日志Aspect
 * 
 * @author wwy
 *
 */
@Aspect
@Component
public class LogAspect {
	
	@Autowired
	private LogService logService;
	
	@Pointcut(value = "@annotation(com.szt.ynb.server.router.annotations.Log)")
	public void log() {
		
	}
	
	@After(value = "log()")
	public void afterLog(JoinPoint joinPoint) throws ClassNotFoundException {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		SessionUser sessionUser = (SessionUser) request.getSession().getAttribute(SessionConst.SESSION_ADMIN);
		Long id = null;
		if (sessionUser != null) {
			id = sessionUser.getId();
		}
		Log log = getAnnotation(joinPoint);
		logService.save(new com.szt.ynb.server.router.entity.Log(id, log.value(), LogType.values()[log.logType()],
				sessionUser.getIp()));
	}
	
	/***
	 * 获得@log注解
	 * 
	 * @param joinPoint
	 * @return
	 * @throws ClassNotFoundException
	 */
	private Log getAnnotation(JoinPoint joinPoint) throws ClassNotFoundException {
		Signature signature = joinPoint.getSignature();
		MethodSignature methodSignature = (MethodSignature) signature;
		Method targetMethod = methodSignature.getMethod();
		return targetMethod.getAnnotation(Log.class);
	}
}
